#include <unistd.h>
#include <string>
#include <iostream>
#include <stdio.h>
#include <errno.h>
#include <sys/wait.h>

// 测试代码：测试管道用于父子进程信息传输的各种情况
int main()
{
    int fds[2];
    pipe(fds);
    pid_t n = fork();

    if (n == 0)
    { // 子进程
        close(fds[0]);
        std::string str = "子进程";
        while (true)
        {
            write(fds[1], str.c_str(), str.size());
            sleep(1);
        }
        std::cout << "子进程正常退出" << std::endl;
        exit(0);
    }
    close(fds[1]);
    char buff[1024] = {0};
    int i = 1;
    int k = 3;
    while (k--)
    {
        buff[0] = 0;
        int j = read(fds[0], buff, 1024);
        if (j > 0)
        {
            std::cout << buff << ':' << i << std::endl;
        }
        else if (j == 0)
        {
            std::cout << "写端关闭" << std::endl;
            break;
        }
        else
        {
            perror("read");
            break;
        }
        i++;
    }
    close(fds[0]);
    int status = 0;
    pid_t f = wait(&status);
    printf("child sig code: %d\n",status&0X7F);
    return 0;
}